package com.hilinos.base.test;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;

import java.io.File;
import java.util.*;
import java.util.function.Consumer;

public class SwaggerUtil {
    public static List<SwaggerTable> getTableList(String filePath) throws Exception {
        List<SwaggerTable> list = new LinkedList<>();
        try {
            File file = new File(filePath);
            String json = jsonRead(file);
            Map map = JSON.parseObject(json, Map.class);
            //得到host，用于模拟http请求
            String host = String.valueOf(map.get("host"));
            String basePath = String.valueOf(map.get("basePath"));
            //解析paths
            JSONObject paths = (JSONObject) map.get("paths");
            if (paths != null) {
                paths.entrySet().iterator().forEachRemaining(new Consumer<Map.Entry<String, Object>>() {
                    @Override
                    public void accept(Map.Entry<String, Object> stringObjectEntry) {

                    }
                });
                Iterator<Map.Entry<String, Object>> iterator = paths.entrySet().iterator();
                while (iterator.hasNext()) {
                    SwaggerTable swaggerTable = new SwaggerTable();
                    List<SwaggerRequest> swaggerRequestList = new LinkedList<>();
                    String requestType = "";

                    Map.Entry<String, Object> next = iterator.next();
                    String url = next.getKey();//得到url
                    JSONObject value = (JSONObject) next.getValue();
                    //得到请求方式，输出结果类似为 get/post/delete/put 这样
                    Set<String> requestTypes = value.keySet();
                    for (String str : requestTypes) {
                        requestType += str + "/";
                    }
                    Iterator<Map.Entry<String, Object>> it2 = value.entrySet().iterator();
                    //解析请求
                    Map.Entry<String, Object> get = it2.next();//得到get
                    JSONObject getValue =(JSONObject) get.getValue();
                    String title = (String) ((List) getValue.get("tags")).get(0);//得到大标题
                    String tag = String.valueOf(getValue.get("summary"));
                    //请求体
                    JSONArray parameters = (JSONArray) getValue.get("parameters");
                    if (parameters != null && parameters.size() > 0) {
                        for (int i = 0; i < parameters.size(); i++) {
                            SwaggerRequest swaggerRequest = new SwaggerRequest();
                            JSONObject param = (JSONObject) parameters.get(i);
                            swaggerRequest.setDescription(String.valueOf(param.get("description")));
                            swaggerRequest.setName(String.valueOf(param.get("name")));
                            swaggerRequest.setType(String.valueOf(param.get("type")));
                            swaggerRequest.setParamType(String.valueOf(param.get("in")));
                            swaggerRequest.setRequire((Boolean) param.get("required"));
                            swaggerRequestList.add(swaggerRequest);
                        }
                    }
                    //返回体，比较固定
                    List<SwaggerResponse> swaggerResponseList = listResponse();
                    //模拟一次HTTP请求,封装请求体和返回体，如果是Restful的文档可以再补充

                    if (requestType.contains("post")) {
                        Map<String, String> stringStringMap = toPostBody(swaggerRequestList);
                        swaggerTable.setRequestParam(stringStringMap.toString());

                        HttpHeaders headers = new HttpHeaders();

                        HttpEntity<Map<String, String>> request = new HttpEntity<>(stringStringMap, headers);
//                        String post = NetUtil.post(host + url, stringStringMap);
//                        String post = restTemplate.postForObject("http://"+host +basePath + url, request,String.class);
//                        swaggerTable.setResponseParam(post);
                    } else if (requestType.contains("get")) {
                        String s = toGetHeader(swaggerRequestList);
                        swaggerTable.setResponseParam(s);
//                        String getStr = NetUtil.get(host + url + s);
//                        String getStr = restTemplate.getForObject(host +basePath + url + s, String.class);
//                        swaggerTable.setResponseParam(getStr);
                    }

                    //封装Table
                    swaggerTable.setTitle(title);
                    swaggerTable.setUrl(url);
                    swaggerTable.setTag(tag);
                    swaggerTable.setResponseForm("application/json");
                    swaggerTable.setRequestType(StringUtils.removeEnd(requestType, "/"));
                    swaggerTable.setSwaggerRequestList(swaggerRequestList);
                    swaggerTable.setSwaggerResponseList(swaggerResponseList);
                    list.add(swaggerTable);
                }
            }
            return list;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    //封装返回信息，可能需求不一样，可以自定义
    private static List<SwaggerResponse> listResponse() {
        List<SwaggerResponse> swaggerResponseList = new LinkedList<SwaggerResponse>();
        swaggerResponseList.add(new SwaggerResponse("受影响的行数", "counts", null));
        swaggerResponseList.add(new SwaggerResponse("结果说明信息", "msg", null));
        swaggerResponseList.add(new SwaggerResponse("是否成功", "success", null));
        swaggerResponseList.add(new SwaggerResponse("返回对象", "data", null));
        swaggerResponseList.add(new SwaggerResponse("错误代码", "errCode", null));
        return swaggerResponseList;
    }

    //封装post请求体
    private static Map<String, String> toPostBody(List<SwaggerRequest> list) {
        Map<String, String> map = new HashMap<>(16);
        if (list != null && list.size() > 0) {
            for (SwaggerRequest swaggerRequest : list) {
                String name = swaggerRequest.getName();
                String type = swaggerRequest.getType();
                switch (type) {
                    case "string":
                        map.put(name, "string");
                        break;
                    case "integer":
                        map.put(name, "0");
                        break;
                    case "double":
                        map.put(name, "0.0");
                        break;
                    default:
                        map.put(name, "null");
                        break;
                }
            }
        }
        return map;
    }

    //封装get请求头
    private static String toGetHeader(List<SwaggerRequest> list) {
        StringBuffer stringBuffer = new StringBuffer();
        if (list != null && list.size() > 0) {
            for (SwaggerRequest swaggerRequest : list) {
                String name = swaggerRequest.getName();
                String type = swaggerRequest.getType();
                switch (type) {
                    case "string":
                        stringBuffer.append(name + "&=string");
                        break;
                    case "integer":
                        stringBuffer.append(name + "&=0");
                        break;
                    case "double":
                        stringBuffer.append(name + "&=0.0");
                        break;
                    default:
                        stringBuffer.append(name + "&=null");
                        break;
                }
            }
        }
        String s = stringBuffer.toString();
        if ("".equalsIgnoreCase(s)) {
            return "";
        }
        return "?" + StringUtils.removeStart(s, "&");
    }

    private static String jsonRead(File file) {
        Scanner scanner = null;
        StringBuilder buffer = new StringBuilder();
        try {
            scanner = new Scanner(file, "utf-8");
            while (scanner.hasNextLine()) {
                buffer.append(scanner.nextLine());
            }
        } catch (Exception e) {

        } finally {
            if (scanner != null) {
                scanner.close();
            }
        }
        return buffer.toString();
    }
}
